// 基础请求封装：统一基地址、Token、错误处理
// export const BASE_URL = uni.getStorageSync('BASE_URL') || 'http://140.207.36.170:1013';
export const BASE_URL = uni.getStorageSync('BASE_URL') || 'http://127.0.0.1:3309';

function getToken() {
	try {
		return uni.getStorageSync('token') || '';
	} catch (e) {
		return '';
	}
} 

export function request({ url, method = 'GET', data = {}, header = {} }) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}${url}`,
			method,
			data,
			header: {
				'Content-Type': 'application/json',
				'Authorization': getToken() ? `Bearer ${getToken()}` : '',
				...header
			},
			success: (res) => {
				const { statusCode, data } = res;
				if (statusCode >= 200 && statusCode < 300) {
					resolve(data);
				} else {
					reject(res);
				}
			},
			fail: (err) => reject(err)
		});
	});
}

export function upload({ url, filePath, name = 'file', formData = {}, header = {} }) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${BASE_URL}${url}`,
			filePath,
			name,
			formData,
			header: {
				'Authorization': getToken() ? `Bearer ${getToken()}` : '',
				...header
			},
			success: (res) => {
				try {
					const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
					resolve(data);
				} catch (e) {
					resolve(res.data);
				}
			},
			fail: (err) => reject(err)
		});
	});
}

export function setBaseUrl(baseUrl) {
	uni.setStorageSync('BASE_URL', baseUrl);
}


